package com.xique.auth.controller;

import com.xique.auth.form.LoginBody;
import com.xique.auth.service.ClientLoginService;
import com.xique.client.api.model.LoginClientUser;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.security.service.ClientTokenService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author shd
 * @create 2021/7/20 16:04
 */
@RestController
@RequestMapping("client")
@ApiModel
public class ClientTokenController {

    @Autowired
    private ClientTokenService clientTokenService;

    @Autowired
    private ClientLoginService clientLoginService;

    @PostMapping("/login")
    @ApiOperation("岗亭登录")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginClientUser userInfo = clientLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(clientTokenService.createToken(userInfo));
    }

    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request)
    {
        LoginClientUser loginUser = clientTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            Long clientId = loginUser.getClientId();
            // 删除用户缓存记录
            clientTokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            clientLoginService.logout(username, clientId);
        }
        return R.ok();
    }

    @PostMapping("/refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginClientUser loginUser = clientTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            clientTokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
}
